package jp.cane.android.luciferblue;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

public class RawFragment extends Fragment {
	public static final String ARG_SECTION_NUMBER = "section_number";

	static protected boolean echo = true;

	private Handler handler = new Handler();
	private View view = null;
	private MainService mBoundService = null;
	private String lastMessage = "";

	public RawFragment() {
	}

	public void setService(MainService boundService) {
		this.mBoundService = boundService;
		updateView();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		View ret = inflater.inflate(R.layout.raw, null);

		Button button = (Button) ret.findViewById(R.id.send);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText edit = (EditText) getActivity().findViewById(
						R.id.editText1);
				String str = edit.getText().toString();
				send(str);
				edit.setText("");
			}
		});

		final ToggleButton polling = (ToggleButton) ret
				.findViewById(R.id.polling);
		if (mBoundService != null && mBoundService.pollingThread != null) {
			polling.setChecked(true);
		}
		polling.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					if (mBoundService != null) {
						mBoundService.startPolling();
					}
				} else {
					if (mBoundService != null) {
						mBoundService.stopPolling();
					}
				}
			}
		});

		this.view = ret;
		return ret;
	}

	private void send(String str) {
		if (this.mBoundService != null) {
			this.mBoundService.send(str, echo);
		}
	}

	public void updateView() {
		if (view == null) {
			return;
		}
		this.handler.post(new Runnable() {
			public void run() {
				{
					TextView text = (TextView) view
							.findViewById(R.id.textView1);
					text.setText(RawFragment.this.lastMessage);
				}
				{
					MainThread thread = mBoundService.getThread();
					String lines = thread.getLog();
					TextView text = (TextView) view.findViewById(R.id.text);
					text.setText(Html.fromHtml(lines));
				}
			}
		});
	}

	public void change(final String str) {
		this.lastMessage = str;
		updateView();
	}
}
